import flask
import flask_login
from flask_login import current_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import check_password_hash, generate_password_hash

from SMTP.SmtpServer import Smtp, Sender, Receiver, SmtpServer
from WEB.app.Decorator.Login import pc_login_required
from WEB.app.forms.Email import get_smtp_form, get_email_template_form
from WEB.app.forms.User import get_login_form, get_register_form
from WEB.app.models import AdminImportEmail, User as Customer, UserSmtp, UserEmailTemplate


class User():
    @pc_login_required
    def index(self):
        """
        前台首页
        :return:
        """

        class EmailData():
            total = None
            send_total = None
            wait_send_total = None

        email = EmailData()
        email.total = AdminImportEmail.query.filter(AdminImportEmail.used_user_id == current_user.get_id()).count()

        email.send_total = AdminImportEmail.query.filter(AdminImportEmail.used_user_id == current_user.get_id(),
                                                         AdminImportEmail.is_send == 1).count()
        email.wait_send_total = AdminImportEmail.query.filter(AdminImportEmail.used_user_id == current_user.get_id(),
                                                              AdminImportEmail.is_send == 0).count()

        return flask.render_template('frontend/index.html', email=email)

    def login(self):
        """
        登录
        :return:
        """
        msg = ''
        form = get_login_form()
        if flask.request.method == 'GET':
            return flask.render_template('frontend/user/login.html', form=form)
        if flask.request.method == 'POST':
            name = flask.request.form.get('name')
            email = flask.request.form.get('email')
            password = flask.request.form.get('password')
            user = Customer.query.filter(Customer.email == email).first()
            if user:
                # 校验密码
                if check_password_hash(user.password, password):
                    # 使用flask_login 实现登陆后的操作
                    flask_login.login_user(user)
                    flask.session['user_id'] = user.get_id()
                    return flask.redirect('/')
                else:
                    msg = '登录密码错误！'
            else:
                msg = '尚未注册！'
        return flask.render_template('frontend/user/login.html', msg=msg, form=form)

    def register(self, db):
        msg = ''
        form = get_register_form()
        if flask.request.method == 'GET':
            return flask.render_template('frontend/user/register.html', form=form)
        if flask.request.method == 'POST':
            name = flask.request.form.get('name')
            email = flask.request.form.get('email')
            password = flask.request.form.get('password')
            user = Customer.query.filter(Customer.email == email).first()
            if user is None:
                user = Customer()
                user.name = name
                user.email = email
                password = generate_password_hash(password)
                user.password = password
                # 记录
                try:
                    db.session.add(user)
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    return str(e)
                return flask.redirect('/login')
            else:
                msg = '该邮箱已注册！'
        return flask.render_template('frontend/user/register.html', msg=msg, form=form)

    def logout(self):
        """
        客户退出
        :return:
        """
        flask_login.logout_user()
        flask.session.clear()
        return flask.redirect('/login')


class Email():
    @pc_login_required
    def send(self, db: SQLAlchemy):
        # smtp信息包装
        smtp_info = UserSmtp.query.filter(UserSmtp.user_id == current_user.get_id(), UserSmtp.active == 1).first()
        if smtp_info is None:
            return flask.redirect('/my/email/smtp')
        print(smtp_info)
        smtp = Smtp()
        smtp.host = smtp_info.host
        smtp.port = smtp_info.port
        smtp.email = smtp_info.email
        smtp.password = smtp_info.password

        # 发送者信息
        sender = Sender()
        template_info = UserEmailTemplate.query.filter(UserEmailTemplate.user_id == current_user.get_id(),
                                                       UserEmailTemplate.active == 1).first()
        if template_info is None:
            return flask.redirect('/my/email/template')
        sender.subject = template_info.subject
        sender.email = smtp_info.email
        sender.nickname = template_info.sender_nickname
        sender.content = template_info.content

        # Smtp服务
        smtp_server = SmtpServer()
        emails = AdminImportEmail.query.filter(AdminImportEmail.used_user_id == current_user.get_id(),
                                               AdminImportEmail.is_send == 0).all()
        send_success_emails = []
        send_error_emails = []
        for email in emails:
            # 接收者信息
            receiver = Receiver()
            receiver.email = email.email
            receiver.nickname = ''

            # 发送消息
            rs = smtp_server.send_email_by_smtp_setting(sender=sender, receiver=receiver, smtp=smtp)
            if rs:
                email.is_send = 1
                try:
                    db.session.merge(email)
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                send_success_emails.append(email)
            else:
                send_error_emails.append(email)

        return flask.render_template('frontend/common/tool/msg.html',
                                     msg='成功发送：' + str(len(send_success_emails)) + '封。发送失败：' + str(
                                         len(send_error_emails)) + '封', time=5, url=flask.url_for('index'))

    @pc_login_required
    def smtp(self, db: SQLAlchemy):
        form = get_smtp_form()
        msg = None
        if flask.request.method == 'GET':
            return flask.render_template('frontend/email/smtp.html', form=form, msg=msg)
        if flask.request.method == 'POST':
            user_smtp = UserSmtp()
            user_smtp.host = flask.request.form.get('host')
            user_smtp.user_id = current_user.get_id()
            user_smtp.port = flask.request.form.get('port')
            user_smtp.email = flask.request.form.get('email')
            user_smtp.password = flask.request.form.get('password')
            user_smtp.active = flask.request.form.get('active')
            # 检测是否已经配置过
            has_smtp = UserSmtp.query.filter(UserSmtp.user_id == current_user.get_id(),
                                             UserSmtp.email == user_smtp.email).first()
            if has_smtp is not None:
                try:
                    has_smtp.host = user_smtp.host
                    has_smtp.port = user_smtp.port
                    has_smtp.password = user_smtp.password
                    has_smtp.active = user_smtp.active
                    db.session.merge(user_smtp)
                    db.session.commit()
                    msg = '更新SMTP配置成功！'
                except Exception as e:
                    db.session.rollback()
                    msg = '更新失败：' + str(e)
            else:
                try:
                    db.session.add(user_smtp)
                    db.session.commit()
                    msg = '新增SMTP配置成功！'
                except Exception as e:
                    db.session.rollback()
                    msg = '新增失败：' + str(e)
        return flask.render_template('frontend/common/tool/msg.html', msg=msg,
                                     url=flask.url_for('index'), time=3)

    @pc_login_required
    def email_template(self, db: SQLAlchemy):
        form = get_email_template_form()
        msg = None
        if flask.request.method == 'GET':
            return flask.render_template('frontend/email/template.html', form=form, msg=msg)
        if flask.request.method == 'POST':
            user_email_template = UserEmailTemplate()
            user_email_template.user_id = current_user.get_id()
            user_email_template.email = flask.request.form.get('email')
            user_email_template.sender_nickname = flask.request.form.get('sender_nickname')
            user_email_template.subject = flask.request.form.get('subject')
            user_email_template.content = flask.request.form.get('content')
            user_email_template.active = flask.request.form.get('active')
            # 检测是否已经配置过
            has_smtp = UserSmtp.query.filter(UserEmailTemplate.user_id == current_user.get_id(),
                                             UserEmailTemplate.id == user_email_template.id).first()
            if has_smtp is not None:
                try:
                    has_smtp.host = user_email_template.host
                    has_smtp.port = user_email_template.port
                    has_smtp.password = user_email_template.password
                    db.session.merge(user_email_template)
                    db.session.commit()
                    msg = '更新模板配置成功！'
                except Exception as e:
                    db.session.rollback()
                    msg = '更新失败：' + str(e)
            else:
                try:
                    db.session.add(user_email_template)
                    db.session.commit()
                    msg = '新增模板配置成功！'
                except Exception as e:
                    db.session.rollback()
                    msg = '新增失败：' + str(e)
        return flask.render_template('frontend/common/tool/msg.html', msg=msg,
                                     url=flask.url_for('index'), time=5)
